package com.len.service;

import com.github.pagehelper.Page;
import com.len.constant.RedisConstant;
import com.len.constant.RedisLockConstant;
import com.len.controller.req.UserReq;
import com.len.core.RedisUtil;
import com.len.entity.UserEntity;
import com.len.template.RedisLockTemplate;
import com.len.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.regex.Pattern;

@Service
public class UserService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private PageService pageService;

    @Resource
    private RedisLockTemplate redisLockTemplate;

    @Resource
    private RedisUtil redisUtil;

    public Page<UserEntity> getList(UserReq req, Page<UserEntity> page) {

        Query query = new Query();
        query.skip((long) (page.getPageNum() - 1) *page.getPageSize());
        query.limit(page.getPageSize());

        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(req.getRegisterBeginTime())&&StringUtils.isNotBlank(req.getRegisterEndTime())){
            criteria.andOperator(Criteria.where("createTime").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getRegisterBeginTime(),"yyyy-MM-dd")))
                    ,Criteria.where("createTime").lt(Integer.parseInt(DateUtil.date2TimeStamp(req.getRegisterEndTime(),"yyyy-MM-dd"))+24*3600));
        }else if (StringUtils.isNotBlank(req.getRegisterBeginTime())){
            criteria.and("createTime").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getRegisterBeginTime(),"yyyy-MM-dd")));
        }else if (StringUtils.isNotBlank(req.getRegisterEndTime())){
            criteria.and("createTime").lt(Integer.parseInt(DateUtil.date2TimeStamp(req.getRegisterEndTime(),"yyyy-MM-dd"))+24*3600);
        }
        if (req.getUserNO()!=null){
            criteria.and("userNO").is(req.getUserNO());
        }
        if (StringUtils.isNotBlank(req.getPhone())){
            Pattern pattern = Pattern.compile("^.*"+req.getPhone()+".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("phone").regex(pattern));
        }
        query.addCriteria(criteria);
        query.with(Sort.by(
                Sort.Order.desc("createTime")
        ));
        List<UserEntity> list = mongoTemplate.find(query, UserEntity.class);
        long total = pageService.count(query, UserEntity.class);

        page.addAll(list);
        page.setTotal(total);
        return page;
    }

    public void updateShowLimit(Integer showLimit, String id) throws Exception {
        redisLockTemplate.call(RedisLockConstant.USER_ID_LOCK.replace("{userId}",id),()->{
            UserEntity userEntity = mongoTemplate.findOne(new Query(Criteria.where("id").is(id)), UserEntity.class);
            if (userEntity!=null){
                mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), Update.update("showLimit", userEntity.getShowLimit()+showLimit), UserEntity.class);
                redisUtil.del(RedisConstant.USER_CACHE.replace("{userId}", id));
            }
            return null;
        });
    }

    public void updateVip(Integer vip, String id) throws Exception {
        redisLockTemplate.call(RedisLockConstant.USER_ID_LOCK.replace("{userId}",id),()->{
            mongoTemplate.updateFirst(new Query(Criteria.where("id").is(id)), Update.update("vip", vip), UserEntity.class);
            redisUtil.del(RedisConstant.USER_CACHE.replace("{userId}", id));
            return null;
        });
    }
}
